<?php

/**
 * Upload
 *
 * @author baziak
 */
class Util_Upload
{
    protected $_basePath = null;
    
    public function __construct($basePath = '')
    {
        $this->_basePath = $basePath;
    }

    public function uploadImage($filename)
    {
        $filename = $this->_basePath . $filename;
        // getting max post size
        // http://php.net/manual/en/features.file-upload.php#73762
        $postMaxSize = ini_get('post_max_size');
        $mul = substr($postMaxSize, -1);
        $mul = $mul == 'M' ? 1048576 : ($mul == 'K' ? 1024
            : ($mul == 'G' ? 1073741824 : 1));

        $postMaxSize = $mul * (int) $postMaxSize;

        // check if posted data is too big
        if (isset($_SERVER['CONTENT_LENGTH'])
            && ($_SERVER['CONTENT_LENGTH'] > $postMaxSize
            && $postMaxSize || $_SERVER['CONTENT_LENGTH'] > 1024 * 1024 * 5))
        {
            require_once 'Util/Upload/SizeException.php';
            throw new Util_Upload_SizeException('File is too big.');
        }
        
        // P.S. I still love PHP

        // upload
//        if ($this->uploadFile("php://input", $filename)
//            || $this->uploadMultipartForm("image", $filename))
//        {
//            return $filename;
//        }
        // if image in request present - decode it from Base64 data and 
        //save inti tmpfile
        if (isset($_POST['image']) && $_POST['image']) {
            $file = base64_decode($_POST['image']);
            
            $f = @fopen($filename, "w");
            
            if ($f !== false) {
                if (fwrite($f, $file) === FALSE) {
                    require_once 'Util/Exception.php';
                    throw new Util_Exception("Can\'t save  tmpfile");
                    return false;
                }
            } else {
                require_once 'Util/Exception.php';
                throw new Util_Exception("The  tmpfile aren't writable");
                return false;
            }
            return null;
        }

        //move_uploaded_file($_FILES['image']['tmp_name'], $filename);
        $this->uploadFile($_FILES['image']['tmp_name'], $filename);
        return null;
    }

    public function uploadFile($source, $dest)
    {
        return @copy($source, $dest);
    }

    public function uploadMultipartForm($name, $dest)
    {
        if (isset($_FILES[$name])) {
            $tmpName = $_FILES[$name]['tmp_name'];
            return rename($tmpName, $dest);
        }

        return false;
    }
}
